package com.yzc.config;

import com.yzc.util.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

@Slf4j
public class MdcFilter implements Filter {
    private final JwtUtil jwtUtil;

    @Autowired
    public MdcFilter(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    private static final Marker LOG_MARKER = MarkerFactory.getMarker("LOG");

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String token = httpRequest.getHeader("Authorization");
            if (token != null && !token.isEmpty()) {
                // 使用 JwtUtil 解析令牌并获取用户名
                String username = jwtUtil.extractUsername(token);

                if (username != null) {
                    MDC.put("username", username);
                }
            }
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error(LOG_MARKER, "MdcFilter 异常", e); // 使用 LOG_MARKER
        } finally {
            MDC.clear(); // 确保在请求处理完成后清除 MDC
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
